package com.caiden_micheal.dynamic.file_management.service.impl;

import com.caiden_micheal.base.domain.AjxResult;
import com.caiden_micheal.base.utils.JwtUtil;
import com.caiden_micheal.base.utils.MinioUtil;
import com.caiden_micheal.base.utils.RedisUtil;
import com.caiden_micheal.dynamic.file_management.dto.DFileRemoveDTO;
import com.caiden_micheal.dynamic.file_management.service.FileManagementService;
import com.caiden_micheal.dynamic.record.mapper.DFileRecordMapper;
import io.jsonwebtoken.Claims;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.util.Objects;

@Service
public class FileManagementServiceImpl implements FileManagementService {
    private static final Logger logger = LoggerFactory.getLogger(FileManagementServiceImpl.class);


    @Autowired
    private MinioUtil minioUtil;
    @Autowired
    private DFileRecordMapper dFileRecordMapper;

    @Override
    public AjxResult fileUpload(String token, String fileName, MultipartFile file) {
        if (token == null || fileName == null || file == null) {
            return AjxResult.paramError("参数传递有误");
        }
        Claims claims = JwtUtil.validateUserToken(token);
        if (claims == null) {
            return AjxResult.jwtError("上传失败，身份校验失败");
        }
        String onlineStatusKey = "caiden_micheal:user:" + claims.get("userId") + ":onlineStatus";
        String onlineStatus = RedisUtil.getValue(onlineStatusKey);
        if (StringUtils.isEmpty(onlineStatus)) {
            return AjxResult.jwtError("上传失败，Token已失效，请重新登录");
        } else if (!Objects.equals(onlineStatus, claims.get("flag"))) {
            return AjxResult.jwtError("Token is used maliciously, and the current behavior has been recorded");
        }
        String uploadedFileName = minioUtil.upload(fileName, file);
        if (uploadedFileName != null) {
            dFileRecordMapper.insert(uploadedFileName);
            return AjxResult.success(uploadedFileName);
        } else {
            return AjxResult.unknownError("上传失败");
        }
    }

    @Transactional
    @Override
    public AjxResult fileRemove(DFileRemoveDTO dFileRemoveDTO) {
        if (dFileRemoveDTO == null || dFileRemoveDTO.getFileName() == null) {
            return AjxResult.paramError("参数传入有误");
        }
        try {
            if (minioUtil.removeFile(dFileRemoveDTO.getFileName()) != null) {
                dFileRecordMapper.remove(dFileRemoveDTO.getFileName());
                return AjxResult.success("删除成功");
            }
            return AjxResult.unknownError("删除失败");
        } catch (Exception e) {
            logger.error(e.toString());
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return AjxResult.unknownError("数据库操作异常");
        }
    }
}
